import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config} from '../../shared/smartadmin.config';

declare var $: any;
declare var echarts: any;
@Component({
	selector: 'sa-statis-order-yf',
	templateUrl: './statis-order-yf.component.html',
	styleUrls:['./statis-order-yf.component.css']
})
export class StatisOrderYFComponent implements OnInit {
	startTime = ''; //过滤条件-开始时间
	endTime = ''; //过滤条件-结束时间
	selectedCompanyId = ''; //过滤条件-公司ID
	selectedCompanyName = ''; //过滤条件-公司名称
	selectedCompanyCode = '';//过滤条件-公司code
	dateType = '1';		//过滤条件-时间类型，默认按天汇总
	
	pieChart:any = '';		//饼图对象
	barChart:any = '';		//柱状图
	colorList = ['#5de2ca', '#f94872', '#ff993e','#a589e8'];	//颜色
	dataList = [];		//柱状图返回的时间参数
	normalList = [];	//正常卸货
	abnormalList = [];	//异常卸货
	norailList = [];	//未配置围栏
	errorList = [];		//设备异常
	// 饼图数据
	allMapNormal:any = '';	//正常卸货
	allMapAbnormal:any = '';		//异常卸货
	allMapNorail:any = '';		//未配置围栏
	allMapError:any = '';		//设备异常
	shortBtnIndex:number = 3;
	companyTreeParam:any = {projectKey:'yf'};
	totalNumber:number = null;	//总订单s
	constructor(private jsonApiService: JsonApiService, private router: Router,private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
		});
	}

	ngOnInit() {
		this.initDate().then(()=>{
			this.load();
		});	
	}
	initDate(){
		var that = this;
		return new Promise(function (resolve, reject) {
			System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(()=>{
					System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(()=>{
						$("#startTime").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							$("#endTime").datetimepicker("setStartDate", e.date);
							that.startTime = $("#startTime").val();
							$("#endTime").datetimepicker("setStartDate", e.date);
						});
						$("#endTime").datetimepicker({//时间插件
							format: "yyyy-mm-dd hh:ii:ss",
						    language: "zh-CN",
						    autoclose: true,
						}).on("changeDate", function(e){
							$("#startTime").datetimepicker("setEndDate", e.date);
							that.endTime = $("#endTime").val();
							$("#startTime").datetimepicker("setEndDate", e.date);
						});
						var date = new Date();
						$("#endTime").val(getTime(date));//当前时间
						date.setMonth(date.getMonth() - 1);//设置前一个月
						$("#startTime").val(getTime(date));
						$('#dateRange').val('4');
						// $('.shortBtn').eq(2).removeClass('btn-link').addClass('btn-primary');
						that.startTime = $("#startTime").val();
						that.endTime = $("#endTime").val();
						$("#startTime").datetimepicker("setEndDate",that.endTime);
						$("#endTime").datetimepicker("setStartDate",that.startTime);
						resolve();
					});
				}
			);
		})

	}
	dateChange(){
		const that = this;
		$('#startTime').val('').change();
		$('#endTime').val('').change();
		$('#startTime').data('datetimepicker').remove();
		$('#endTime').data('datetimepicker').remove();
		this.startTime = '';
		this.endTime = '';
		this.shortBtnIndex = 0;
		let title,viewNumber,formatType;
		if(this.dateType == '1'){
			title = '按天汇总';
			formatType = 'yyyy-mm-dd hh:ii:ss';
			viewNumber = 0;
			$("#startTime").datetimepicker({//时间插件
				format: formatType,
				language: "zh-CN",
				autoclose: true,
				minView:viewNumber,
			}).on("changeDate", function(e){
				var date = e.date;
				if(!date){return;};
				var time = getTime(date);
				$("#endTime").datetimepicker("setStartDate", time);
			});
			$("#endTime").datetimepicker({//时间插件
				format: formatType,
				language: "zh-CN",
				autoclose: true,
				minView:viewNumber,
			}).on("changeDate", function(e){
				var date = e.date;
				if(!date){return;}
				var time = getTime(date);
				$("#startTime").datetimepicker("setEndDate", time);
			});
			var date = new Date();
			$("#endTime").val(getTime(date));//当前时间
			date.setMonth(date.getMonth() - 1);//设置前一个月
			$("#startTime").val(getTime(date));
			$('#dateRange').val('4');
			that.startTime = $("#startTime").val();
			that.endTime = $("#endTime").val();
			that.shortBtnIndex = 3;		//选中按天汇总
		}
		if(this.dateType == '2'){
			title = '按月汇总';
			formatType = 'yyyy-mm';
			viewNumber = 3;
			$("#startTime").datetimepicker({//时间插件
				format: formatType,
				language: "zh-CN",
				autoclose: true,
				minView:viewNumber,
				startView:viewNumber
			}).on("changeDate", function(e){
				var date = e.date;
				if(!date){return;};
				var time = getTime(date);
				$("#endTime").datetimepicker("setStartDate", time);
			});
			$("#endTime").datetimepicker({//时间插件
				format: formatType,
				language: "zh-CN",
				autoclose: true,
				minView:viewNumber,
				startView:viewNumber
			}).on("changeDate", function(e){
				var date = e.date;
				if(!date){return;}
				var time = getTime(date);
				$("#startTime").datetimepicker("setEndDate", time);
			});
		}
		if(this.dateType == '3'){
			title = '按年汇总';
			formatType = 'yyyy';
			viewNumber = 4;
			$("#startTime").datetimepicker({//时间插件
				format: formatType,
				language: "zh-CN",
				autoclose: true,
				minView:viewNumber,
				startView:viewNumber
			}).on("changeDate", function(e){
				var date = e.date;
				if(!date){return;};
				var time = getTime(date);
				$("#endTime").datetimepicker("setStartDate", time);
			});
			$("#endTime").datetimepicker({//时间插件
				format: formatType,
				language: "zh-CN",
				autoclose: true,
				minView:viewNumber,
				startView:viewNumber
			}).on("changeDate", function(e){
				var date = e.date;
				if(!date){return;}
				var time = getTime(date);
				$("#startTime").datetimepicker("setEndDate", time);
			});
		}
		$("#startTime").datetimepicker("setEndDate",$('#endTime').val());
		$("#endTime").datetimepicker("setStartDate",$('#startTime').val());
		let option = {
			title: {
				text: title,
				left: 'center'
			}
		}
		this.barChart.setOption(option);
		
	}
	//清除所选时间
	del_date(){
		this.startTime='';
		this.endTime='';
		$("#startTime").val('').change();
		$("#endTime").val('').change();
		$("#endTime").datetimepicker("setStartDate", null);
		$("#startTime").datetimepicker("setEndDate", null);
	}
	// 初始化饼图
	initPie(){
		this.pieChart = echarts.init(document.getElementById('pieChart'));
		var option = {
			color: this.colorList,
			title: {
				//text: '区间汇总汇总',
				left: 'center',
				top:20
			},
			tooltip: {
				formatter: '{b} : {c} ({d}%)'
			},
	//	    legend: {
	//	        bottom: 10,
	//	        left: 'center',
	//	        data: ['正常卸货', '异常卸货', '未配置围栏', '设备异常'],
	//	    },
			series: [
				{
					type: 'pie',
					radius: '55%',
					center: ['50%', '50%'],
					selectedMode: 'single',
					tilt:0.8,
					stroke: {
						color: '#fff',
						width: 2
					},
					itemStyle: { //图形样式
						normal: {
							borderColor: '#ffffff',
							borderWidth: 2,
						},
					},
					label:{
						 normal: {
							 formatter: '{b}\n{d}%'
						},
					},
					labelLine: {
			            normal: {
			                length: 10,
			                length2: 10,
			            }
			        },
					data: [
						{
							value: this.allMapNormal,
							name: '正常卸货',
						},
						{value: this.allMapAbnormal, name: '异常卸货'},
						{value: this.allMapNorail, name: '未配置围栏'},
						{value: this.allMapError, name: '设备异常'}
					],
					emphasis: {
						itemStyle: {
							shadowBlur: 5,
							shadowOffsetX: 0,
							shadowColor: 'rgba(0, 0, 0, 0.5)'
						}
					}
				}
			]
		};
		
		this.pieChart.setOption(option);
		$(window).resize(this.pieChart.resize);
	}
	// 初始化柱状图
	initBar(){
		var seriesLabel = {
			'normal': {
				show: false,
				textBorderWidth: 2,
				position:'top',
				color:'#000000'
			}
		}
		this.barChart = echarts.init(document.getElementById('columnChart'));
		 var option = {
			title: {
				text: '按天汇总',
				left: 'center'
			},
			color: this.colorList,
			backgroundColor:'#fefefe',
			barGap:'10%',
			grid: {
				top:'80',
				left:'60',
				right:'12'
			},
			dataZoom: [
				{
					id: 'dataZoomX',
					type: 'slider',
					xAxisIndex: [0],
					filterMode: 'filter'
				},
				{
					type: 'inside',
				},
			],
			tooltip: {
				 trigger: 'axis',
				 axisPointer: {
					 type:'shadow'
				 }
			},
			legend: {
				data: ['正常卸货', '异常卸货', '未配置围栏', '设备异常'],
				top:25
			},
			xAxis: [
				{
					type: 'category',
					axisTick: {show: false},
					data: this.dataList,
					//name:'时间'
				}
			],
			yAxis: [
				{
					type: 'value',
					//name:'数量'
				}
			],
			series: [
				{
					name: '正常卸货',
					type: 'bar',
					label:seriesLabel,
					barGap: 0,
					data:this.normalList
				},
				{
					name: '异常卸货',
					type: 'bar',
					label: seriesLabel,
					data:this.abnormalList
				},
				{
					name: '未配置围栏',
					type: 'bar',
					label: seriesLabel,
					data:this.norailList
				},
				{
					name: '设备异常',
					type: 'bar',
					label:seriesLabel,
					data:this.errorList
				},
			]
		};
		 this.barChart.setOption(option);
		 $(window).resize(this.barChart.resize);
	}
	
	//刷新
	table_search(){
    	this.load();
   	}
	//初始化加载list数据
	load() {
		if(!this.endTime || !this.startTime){
			this.jsonApiService.message('时间不能为空');
			return false;
		}
		let endValue = '',startValue='';
		if(this.dateType == '1'){		//按日汇总
			startValue = this.startTime;
			endValue = this.endTime;
		}
		if(this.dateType == '2'){		//按月汇总
			startValue = this.startTime + '-01 00:00:00';
		
			let monLastDay:any = '';
			let yeaNumber = Number(this.endTime.split('-')[0]);		//年份
			let monNumber = Number(this.endTime.split('-')[1]);		//月份
			if(yeaNumber%4==0 && yeaNumber%100!=0 || yeaNumber%400==0 ){	//闰年2月有29号	，世纪闰年百年平年		
				if(monNumber == 1 || monNumber ==3 || monNumber ==5 || monNumber ==7 || monNumber ==8 || monNumber == 10|| monNumber == 12){	
					monLastDay = 31;
				}
				if(monNumber == 4||monNumber ==6 || monNumber ==9 || monNumber ==11){
					monLastDay = 30;
				}
				if(monNumber == 2){
					monLastDay = 29;
				}
			}else{		//平年
				if(monNumber == 1 || monNumber ==3 || monNumber ==5 || monNumber ==7 || monNumber ==8 || monNumber == 10|| monNumber == 12){
					monLastDay = 31;
				}
				if(monNumber == 4 || monNumber ==6 || monNumber ==9 || monNumber ==11){
					monLastDay = 30;
				}
				if(monNumber == 2){
					monLastDay = 28;
				}
			}
			
			endValue = this.endTime + '-' + monLastDay +' 23:59:59';
			
		}
		if(this.dateType == '3'){		//按年汇总
			startValue = this.startTime + '-01-01 00:00:00';
			endValue = this.endTime + '-12-31 23:59:59';
		}
		
		let reqData = {
			'projectKey':'yf',
			'startTime':startValue,
			'endTime':endValue,
			'type':this.dateType,
			'companyCode':this.selectedCompanyCode,
		}
		this.jsonApiService.http_obj("orderFlowByOutsideCall/countOrderByCompany.html",reqData).subscribe(result => {
			if(result.success&&result.data.allMap){
				this.allMapNormal = result.data.allMap.normal;
				this.allMapAbnormal = result.data.allMap.abnormal;
				this.allMapError = result.data.allMap.error;
				this.allMapNorail = result.data.allMap.norail;
				this.totalNumber = this.allMapNormal + this.allMapAbnormal + this.allMapError + this.allMapNorail;
				
				let dateCount = result.data.dateCount;
				
				this.dataList.length = 0;
				this.normalList.length = 0;
				this.abnormalList.length = 0;
				this.errorList.length = 0;
				this.norailList.length = 0;
				for(let item in dateCount){
					this.dataList.push(item);
					this.normalList.push(dateCount[item].normal);
					this.abnormalList.push(dateCount[item].abnormal);
					this.errorList.push(dateCount[item].error);
					this.norailList.push(dateCount[item].norail);
				}
				this.initPie();	//渲染饼图
				this.initBar();	//渲染柱状图
			}
		});
	}
	//公司选中回调
	companySelected(data){
		this.selectedCompanyId = data.companyId;
		this.selectedCompanyName = data.companyName;
		this.selectedCompanyCode = data.companyCode;
		this.load();
	}
	shortIcon(val){
		this.shortBtnIndex = val;
		this.dateType = '1';
		switch (val){
			case '1':
				var date = new Date();
				$("#endTime").val(getTime(date));
				date.setDate(date.getDate() - 10);
				$("#startTime").val(getTime(date));
				this.startTime = $("#startTime").val();
				this.endTime = $("#endTime").val();
				this.load();
				this.initDay();
				break;
			case '2':
				var date = new Date();
				$("#endTime").val(getTime(date));
				date.setDate(date.getDate() - 20);
				$("#startTime").val(getTime(date));
				this.startTime = $("#startTime").val();
				this.endTime = $("#endTime").val();
				this.load();
				this.initDay();
				break;
			case '3':
				var date = new Date();
				$("#endTime").val(getTime(date));
				date.setDate(date.getDate() - 30);
				$("#startTime").val(getTime(date));
				this.startTime = $("#startTime").val();
				this.endTime = $("#endTime").val();
				this.load();
				this.initDay();
				break;
			default:
				break;
		}
	}
	initDay(){
		const that = this;
		$('#startTime').data('datetimepicker').remove();
		$('#endTime').data('datetimepicker').remove();
		let title = '按天汇总';
		let formatType = 'yyyy-mm-dd hh:ii:ss';
		let viewNumber = 0;
		$("#startTime").datetimepicker({//时间插件
			format: formatType,
			language: "zh-CN",
			autoclose: true,
			minView:viewNumber,
		}).on("changeDate", function(e){
			var date = e.date;
			if(!date){return;};
			var time = getTime(date);
			$("#endTime").datetimepicker("setStartDate", time);
		});
		$("#endTime").datetimepicker({//时间插件
			format: formatType,
			language: "zh-CN",
			autoclose: true,
			minView:viewNumber,
		}).on("changeDate", function(e){
			var date = e.date;
			if(!date){return;}
			var time = getTime(date);
			$("#startTime").datetimepicker("setEndDate", time);
		});
		$("#startTime").datetimepicker("setEndDate",$('#endTime').val());
		$("#endTime").datetimepicker("setStartDate",$('#startTime').val());
		let option = {
			title: {
				text: title,
				left: 'center'
			}
		}
		this.barChart.setOption(option);
	}
}